package com.example.androidcaculator.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;


import com.example.androidcaculator.R;
import com.example.androidcaculator.utils.Calculator;

import java.lang.reflect.Method;


/*
   存在的未解决的问题：

   切换横竖屏后无自动跳转activity
   整数运算时无法输出整数
   将函数运用于运算公式中
   没解决连续输入小数点
   计算结果为0后，再次输入小数点时界面只输出一个小数点
   输出是无限小数时输出太长
   进制转换器中二进制数值太长会把按键顶到下面去

 */
public class MainActivity extends AppCompatActivity {

    public static final String EXIST = "exist";
    private Button btn[] = new Button[10];
    private Button add, sub, mul, div,
            rmd, left, right,
            reciprocal, squared, root,
            point, equal, back, clear;

    private EditText result;

    //设置一个新变量来修改呈现的界面元素的原因是在用户输入出错时再次输入时可以快速退出那个错误的状态从而正常输入
    private String input = new String();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //获取界面元素
        btn[0] = findViewById(R.id.num0);
        btn[1] = findViewById(R.id.num1);
        btn[2] = findViewById(R.id.num2);
        btn[3] = findViewById(R.id.num3);
        btn[4] = findViewById(R.id.num4);
        btn[5] = findViewById(R.id.num5);
        btn[6] = findViewById(R.id.num6);
        btn[7] = findViewById(R.id.num7);
        btn[8] = findViewById(R.id.num8);
        btn[9] = findViewById(R.id.num9);
        add = findViewById(R.id.btnAdd);
        sub = findViewById(R.id.btnSub);
        mul = findViewById(R.id.btnMul);
        div = findViewById(R.id.btnDiv);
        rmd = findViewById(R.id.btnRmd);
        left = findViewById(R.id.btnLeft);
        right = findViewById(R.id.btnRight);
        reciprocal = findViewById(R.id.btnReciprocal);
        squared = findViewById(R.id.btnSquared);
        root = findViewById(R.id.btnRoot);
        point = findViewById(R.id.btnPoint);
        equal = findViewById(R.id.btnEqual);
        back = findViewById(R.id.btnBack);
        clear = findViewById(R.id.btnClear);
        result = findViewById(R.id.result);


    }


    //主界面生成菜单
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.option_menu, menu);
        return true;
    }

    //当用户点击菜单某项时
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();
        Intent intent;
        switch (id) {
            case R.id.action_scientific:
                intent = new Intent(MainActivity.this, ScientificActivity.class);
                startActivity(intent);
                break;

            //转换器的选项
            case R.id.transform_length:
                intent = new Intent(MainActivity.this, ConverterLengthActivity.class);
                startActivity(intent);
                break;
            case R.id.transform_base:
                intent = new Intent(MainActivity.this, ConverterBaseActivity.class);
                startActivity(intent);
                break;
            case R.id.transform_currency:
                intent = new Intent(MainActivity.this, ConverterCurrencyActivity.class);
                startActivity(intent);
                break;

            case R.id.transform_volume:
                intent = new Intent(MainActivity.this, ConverterVolumeActivity.class);
                startActivity(intent);
                break;
            case R.id.action_dateCal:
                intent = new Intent(this, DateActivity.class);
                startActivity(intent);
                break;

            case R.id.action_help:
                AlertDialog.Builder helpTxt = new AlertDialog.Builder(MainActivity.this);
                helpTxt.setMessage("这里是帮助文档\n本计算器由Dio开发").setTitle("Help");
                helpTxt.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                });
                helpTxt.show();

                break;
            case R.id.action_exit:
                finish();

        }
        return super.onOptionsItemSelected(item);
    }

    //显示菜单项的图标
    @Override
    public boolean onMenuOpened(int featureId, Menu menu) {
        if (menu != null) {
            if (menu.getClass().getSimpleName().equalsIgnoreCase("MenuBuilder")) {
                try {
                    Method method = menu.getClass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);
                    method.setAccessible(true);
                    method.invoke(menu, true);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
        return super.onMenuOpened(featureId, menu);
    }

    //重写该方法实现退出所有Activity的功能
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent != null) {
            boolean isExist = intent.getBooleanExtra(EXIST, false);
            if (isExist)
                this.finish();

        }
    }

    //点击数字按钮时显示数字
    public void getNum(View view) {
        int id = view.getId();
        String value = String.valueOf(result.getText());

        switch (id) {
            case R.id.num1:
                input += "1";
                break;
            case R.id.num2:
                input += "2";
                break;
            case R.id.num3:
                input += "3";
                break;
            case R.id.num4:
                input += "4";
                break;
            case R.id.num5:
                input += "5";
                break;
            case R.id.num6:
                input += "6";
                break;
            case R.id.num7:
                input += "7";
                break;
            case R.id.num8:
                input += "8";
                break;
            case R.id.num9:
                input += "9";
                break;

        }
        result.setText(input);
        if (id == R.id.num0) {
            if (!value.equals("0")) {
                input += "0";
                result.setText(input);
            } else
                result.setText("0");
        }
    }


    //点击功能性按钮时对应操作
    public void getFeature(View view) {
        int id = view.getId();
        String value = String.valueOf(result.getText());
        if (value.charAt(value.length() - 1) >= '0' && value.charAt(value.length() - 1) <= '9' || value.charAt(value.length() - 1) == ')') {
            Calculator cal = new Calculator();
            switch (id) {
                case R.id.btnAdd:
                    input += "+";
                    result.setText(input);
                    break;
                case R.id.btnSub:
                    input += "-";
                    result.setText(input);
                    break;
                case R.id.btnMul:
                    input += "×";
                    result.setText(input);
                    break;
                case R.id.btnDiv:
                    input += "÷";
                    result.setText(input);
                    break;
                case R.id.btnRmd:
                    input += "%";
                    result.setText(input);
                    break;
                case R.id.btnReciprocal:
                    if (cal.isNum(value) && !value.equals("0")) {
                        double res = 1 / Double.parseDouble(value);
                        result.setText(String.valueOf(res));

                    }
                    else if (value.equals("0"))
                        result.setText("除数不能为0");
                    else {
                        result.setText("只能对数字使用该函数");
                    }
                    input = "";
                    break;

                case R.id.btnSquared:
                    cal = new Calculator();
                    if (cal.isNum(value)) {
                        double res = Double.parseDouble(value)*Double.parseDouble(value);
                        result.setText(String.valueOf(res));

                    }else {
                        result.setText("只能对数字使用该函数");
                    }
                    input = "";
                    break;
                case R.id.btnRoot:
                    cal = new Calculator();
                    if (cal.isNum(value)) {
                        double res = Math.sqrt(Double.parseDouble(value));
                        result.setText(String.valueOf(res));

                    }else {
                        result.setText("只能对数字使用该函数");
                    }
                    input = "";
                    break;
                case R.id.btnPoint:
                    if (value.equals("0") && input.equals(""))
                        input += "0.";
                    else input += ".";
                    result.setText(input);
                    break;

            }

        }

        if (id == R.id.btnEqual) {
            Calculator cal = new Calculator();
            if (cal.isNum(value)) {
                //如果没有选择任何一种操作，则直接在数字后加上引号
                input += "=";
                result.setText(input);
            } else {
                //如果有选择了操作，则计算结果
                double res;
                res = cal.calculate(value);
                input = String.valueOf(res);
                result.setText(input);

            }

        }

        if (id == R.id.btnClear) {
            result.setText("0");
            input = new String();
        }

        if (id == R.id.btnBack) {

            if (value.length()>1){
                input = input.substring(0, input.length() - 1);
                result.setText(input);
            }else {
                result.setText("0");
                input = "";
            }

        }

        if (id == R.id.btnLeft) {
            input += "(";
            result.setText(input);
        }
        if (id == R.id.btnRight) {
            //这里可以判断是否出现了左括号，如果没有出现左括号就不能添加右括号
            input += ")";
            result.setText(input);

        }


    }



}